/*
 * Create:      柿子
 * CreateDate:  2023/03/06
 * Describe：   供应商审核记录
 * */
import React, { Component } from 'react';
import { Modal, Row, Col, Card, Checkbox, Empty } from 'antd';
import { Util } from 'tools';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import '../style/index.less';

class SupplierAuditRecord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      propsRecord: {},
      loading: false,
      tableData: [],
      columns: [],
      totalWidth: 1200,
      tabList: [],
      activeKey: '1',
      modifyComparisonColumns: [],
      modifyComparisonTotalWidth: 350,
      modifyComparisonTableData: [],
      modifyComparisonLoading: false,
      detailColumns: [],
      detailTotalWidth: 0,
      detailLoading: false,
      detailTableData: [],
      checked: true,
      rowID: '',
      pageSize: 20,
      page: 1,
      detailRowID: ''
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    //该方法内禁止访问this
    if (('columns' in nextProps && (JSON.stringify(nextProps.columns) !== JSON.stringify(prevState.detailColumns)))) {
      //通过对比nextProps和prevState，返回一个用于更新状态的对象
      return {
        detailTotalWidth: nextProps?.totalWidth || 500,
        detailColumns: nextProps.columns
      }
    }
    //不需要更新状态，返回null
    return null
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  }

  // 修改弹窗状态
  modifyVisible = (visible, record) => {
    const { columns, modifyComparisonColumns } = this.state;
    if (visible && !(columns && columns.length > 0)) {
      this.getTableColumns();
    }
    if (visible && !(modifyComparisonColumns && modifyComparisonColumns.length > 0)) {
      this.getModifyComparisonColumns();
    }
    // visible && record && (record[propsRowIDIndex] !== propsRecord[propsRowIDIndex]) // 同一条记录不自动刷新
    if (visible) {
      this.setState({ visible, propsRecord: record }, () => {
        this.handleQuery();
      });
    } else {
      this.setState({ visible });
    }
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SupplierAuditRecord',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              if (item.dataIndex === 'statusDesc' && (text === '审核拒绝' || text === '拒绝')) { // 状态
                return (
                  <span className="common-record-delete-span">{text}</span>
                );
              } else {
                return text;
              }
            }
          }
        })
        this.setState({ columns, totalWidth: res.totalWidth });
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 获取列表表头数据
  getModifyComparisonColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'FormModificationComparison',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({ modifyComparisonColumns: columns, modifyComparisonTotalWidth: res.totalWidth });
      }
    } catch (error) {
      console.log(error);
    }
  }

  handleTabChange = (activeKey) => {
    this.setState({ activeKey });
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }

  getTableData = async () => {
    try {
      const { auditTableCode, propsRowIDIndex, rowIDDataIndex } = this.props;
      this.setState({ loading: true });
      const { propsRecord, pageSize, page } = this.state;
      let data = {
        params: [{
          [propsRowIDIndex || 'vendorID']: propsRecord[propsRowIDIndex],
        }],
        pagination: [{
          pageSize,
          currentPage: page,
        }]
      }
      let res = await React.$asyncPost(this, auditTableCode || '17060089', data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || []);
      let rowID = '';
      if (tableData && tableData.length > 0) {
        rowID = tableData[0][rowIDDataIndex];
      }
      this.setState({ tableData, total: res.result?.total || 0, loading: false, rowID, modifyComparisonTableData: [], detailTableData: [] }, () => {
        rowID && this.queryRowDataByID();
      });
    } catch (error) {
      this.setState({ loading: false });
    }
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 仅查看变化
  handleViewChanges = (e) => {
    this.setState({ checked: e.target.checked });
  }

  // 操作行
  onClickRowPublic = (record) => {
    const { rowIDDataIndex } = this.props;
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record[rowIDDataIndex]))) {
          this.setState({ rowID: record[rowIDDataIndex] }, () => {
            this.queryRowDataByID();
          });
        } else {
          this.setState({ rowID: '' });
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    const { rowIDDataIndex } = this.props;
    return record[rowIDDataIndex] === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 根据行ID获取明细数据
  queryRowDataByID = async () => {
    try {
      let { tabList, detailCode, rowIDDataIndex, detailTableDataIndex } = this.props;
      const { rowID, activeKey } = this.state;
      activeKey === '1' ? this.setState({ modifyComparisonLoading: true }) : this.setState({ detailLoading: true });
      let data = {
        params: [{
          [rowIDDataIndex || 'optVendorRecordID']: rowID,
        }]
      }
      let res = await React.$asyncPost(this, detailCode || '17060090', data);
      let modifyComparisonTableData = Util.addKeyValueToDataSource(res.result && 'baseArr' in res.result ? (res.result?.baseArr || []) : (Array.isArray(res.result) ? res.result : []));
      let detailTableData = Util.addKeyValueToDataSource(detailTableDataIndex ? (res.result && detailTableDataIndex in res.result ? (res.result[detailTableDataIndex] || []) : []) : []);
      // console.log("modifyComparisonTableData", modifyComparisonTableData)
      // console.log("detailTableData", detailTableData)
      let nActiveKey = activeKey;
      if (!(modifyComparisonTableData && modifyComparisonTableData.length > 0)) {
        nActiveKey = '2';
        tabList = tabList.filter((item => item.key !== '1'))
      }
      if (!(detailTableData && detailTableData.length > 0)) {
        nActiveKey = '1';
        tabList = tabList.filter((item => item.key !== '2'))
      }
      this.setState({ modifyComparisonTableData, detailTableData, tabList, modifyComparisonLoading: false, detailLoading: false, activeKey: nActiveKey });
    } catch (error) {
      this.setState({ modifyComparisonLoading: false, detailLoading: false });
    }
  }

  // 选中行操作
  handleProductRowClick = (record) => {
    const { detailRowIDDataIndex } = this.props;
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.detailRowID === '' || (this.state.detailRowID && (this.state.detailRowID !== record[detailRowIDDataIndex || 'key']))) {
          this.setState({ detailRowID: record[detailRowIDDataIndex || 'key'] });
        } else {
          this.setState({ detailRowID: '' });
        }
      }
    }
  }

  handleDetailRowClassName = (record) => {
    const { detailRowIDDataIndex, statusFlagIndex } = this.props;
    return record[detailRowIDDataIndex || 'key'] === this.state.detailRowID ? 'clickRowStyle' : (record[statusFlagIndex || 'statusFlag'] === 'I' ? 'optometry-add-row-color' : (record[statusFlagIndex || 'statusFlag'] === 'D' ? 'optometry-delete-row-color' : ''));
  }

  filterDetailTableData = () => {
    const { statusFlagIndex } = this.props;
    const { checked } = this.state;
    let detailTableData = JSON.parse(JSON.stringify(this.state.detailTableData));
    if (checked) {
      detailTableData = detailTableData.filter(item => item[[statusFlagIndex || 'statusFlag']] !== 'N');
    }
    return detailTableData
  }

  render() {
    const { visible, tabList, activeKey, loading, tableData, totalWidth, columns, modifyComparisonColumns, modifyComparisonTotalWidth, modifyComparisonLoading, detailLoading, modifyComparisonTableData,
      detailTotalWidth, detailColumns, checked, page, total, rowID
    } = this.state;
    return (
      <Modal
        width="1300px"
        title="审核记录"
        className="supplier-audit-record"
        footer={null}
        visible={visible}
        bodyStyle={{ padding: 12 }}
        onCancel={() => this.modifyVisible(false)}
      >
        <div className="table-body-height">
          <Row>
            <Col span={9}>
              <div style={{ paddingRight: '12px', position: 'relative', height: '100%' }}>
                <PubilcTablePagination
                  param={{
                    page,
                    total,
                    loading,
                    columns, // 表头配置
                    pageSize: '20',
                    data: tableData, // 表格数据
                    x: totalWidth, // 表格的宽度
                    y: 606,
                    height: 656,
                    componentName: 'SupplierAuditRecord',
                  }}
                  compilePage={this.compilePage}
                  getColumns={this.getTableColumns}
                  onClickRowPublic={this.onClickRowPublic}
                  setRowClassNamePublic={this.setRowClassNamePublic}
                />
              </div>
              <div className="common-card-right-split-line" style={{ width: 12, background: '#fff' }}></div>
            </Col>
            <Col span={15}>
              <Card
                size="small"
                className="sm-card-tabs"
                bordered={false}
                tabList={tabList}
                activeTabKey={activeKey}
                tabBarExtraContent={(
                  <div style={{ display: activeKey === '2' ? 'flex' : 'none' }} className="flex-align-items">
                    <span style={{ display: 'inline-block', width: '16px', height: '16px', marginRight: '6px', background: '#b9eddf', borderRadius: '2px' }}></span>本次新增
                    <Checkbox style={{ marginLeft: '24px' }} checked={checked} onChange={this.handleViewChanges}>仅查看变化</Checkbox>
                  </div>
                )}
                onTabChange={this.handleTabChange}
              >
                {activeKey === '1' ? (
                  modifyComparisonTableData && modifyComparisonTableData.length > 0 ? (
                    <PubilcTablePagination
                      param={{
                        y: 550,
                        height: 600,
                        componentName: 'FormModificationComparison',
                        loading: modifyComparisonLoading,
                        data: modifyComparisonTableData, // 表格数据
                        x: modifyComparisonTotalWidth, // 表格的宽度
                        columns: modifyComparisonColumns, // 表头配置
                      }}
                      getColumns={this.getModifyComparisonColumns}
                    />
                  ) : <Empty style={{ marginTop: 100 }} description={rowID ? '暂无数据' : '请选择左侧审核记录查看审核详情'} />
                ) : (activeKey === '2' ? (
                  <PubilcTablePagination
                    param={{
                      y: 550,
                      height: 600,
                      x: detailTotalWidth, // 表格的宽度
                      loading: detailLoading,
                      data: this.filterDetailTableData(), // 表格数据
                      columns: detailColumns, // 表头配置
                    }}
                    onClickRowPublic={this.handleProductRowClick}
                    setRowClassNamePublic={this.handleDetailRowClassName}
                  />
                ) : '')}
              </Card>
            </Col>
          </Row>
        </div>
      </Modal>
    )
  }
};

export default SupplierAuditRecord;